<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form inline :model="queryParams">
            <el-form-item label="机型" prop="aircraftModel">
              <el-select v-model="queryParams.aircraftModel">
                <el-option v-for="(item, index) in airModelList" :key="'model-item' + index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="批次号" prop="track">
              <el-input v-model="queryParams.track" placeholder="请输入" maxlength="20" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['origin:installation:upload']" type="primary" @click="handleOriginUpload()">上传</el-button>
            <el-button v-hasPermi="['origin:installation:delete']" type="primary" @click="handleDelete()">删除</el-button>
            <el-button v-hasPermi="['origin:installation:generate']" type="primary" :loading="buttonLoading" @click="handleGenerateStandard()"
              >生成标准装机清单</el-button
            >
          </el-col>
          <!-- <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar> -->
        </el-row>
      </template>

      <el-table ref="roleTableRef" v-loading="loading" :data="tableDatas" row-key="id" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" reserve-selection />
        <el-table-column label="上传日期" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件名" prop="originalName" :show-overflow-tooltip="true" min-width="200" />
        <el-table-column label="数据条数" prop="detailCnt" width="100" />
        <el-table-column label="是否全机" prop="groupType" width="100">
          <template #default="scope"> {{ scope.row.aircraftModel }}-{{ scope.row.groupType ? scope.row.groupType : '全机' }} </template>
        </el-table-column>
        <el-table-column label="所属机型" prop="aircraftModel" width="100" />
        <el-table-column label="所属批次" prop="track" width="100" />
        <el-table-column label="备注" prop="trackDesc" width="100" />
        <el-table-column label="是否生成标准装机清单" prop="status" width="100">
          <template #default="scope">
            <span v-if="scope.row.status === 'DONE' && scope.row.bizStep === 'OBOM_SBOM_CONVERT'" style="color: #039d12">已生成</span>
            <span v-else style="color: #f59a23">未生成</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button v-hasPermi="['origin:installation:view']" link type="primary" @click="handleDataView(scope.row)">数据查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 上传原始装机清单 -->
    <el-dialog v-model="originDialog.visible" :title="originDialog.title" width="800px" append-to-body>
      <el-form ref="dialogFormRef" :model="dialogForm" label-width="160px" :rules="rules" size="small">
        <el-form-item label="机型" prop="aircraftModel">
          <el-select v-model="dialogForm.aircraftModel" @change="handleFieldChange">
            <el-option v-for="(item, index) in airModelList" :key="'model-item' + index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属批次" prop="track">
          <!-- <el-input v-model="dialogForm.track" placeholder="请输入批次号" maxlength="20"></el-input> -->
          <el-select
            v-model="dialogForm.track"
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="请输入批次"
            @change="handleFieldChange"
          >
            <el-option v-for="item in trackOptions" :key="item.mark" :label="item.name" :value="item.mark" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="file" class="upload-item">
          <el-upload
            style="width: 80%"
            :accept="fileType"
            action=""
            :auto-upload="false"
            :before-upload="handleBefore"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :on-change="handleChange"
          >
            <el-button type="primary">选择上传</el-button>
            <template v-if="fileType" #tip>
              <div class="el-upload__tip">支持扩展名：.xls、.xlsx</div>
            </template>
          </el-upload>
          <el-button type="text" size="small" class="download-template" @click="handleDownloadTemplate">下载模板</el-button>
        </el-form-item>
        <el-form-item label="是否为全机数据" prop="isAll">
          <el-radio-group v-model="dialogForm.isAll">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!dialogForm.isAll" label="所属部段" prop="groupType">
          <!-- <el-input v-model="dialogForm.groupType" placeholder="请输入所属部段"></el-input> -->
          <el-select
            v-model="dialogForm.groupType"
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="请输入所属部段"
          >
            <el-option v-for="item in groupTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input v-model="dialogForm.desc" type="textarea" placeholder="请输入备注" maxlength="200"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleSure">确 定</el-button>
          <el-button :loading="buttonLoading" @click="handleCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="confirmVisible" title="提示" width="500px" append-to-body>
      标准装机清单已生成完毕，请到<span class="dialog-btn" @click="handleView">标准装机清单列表</span>中进行查看！
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OriginInstallationList" lang="ts">
import { getStructureTree } from '@/api/elementsLibrary/index';
import {
  uploadOriginListData,
  getOriginList,
  originalInfoDelete,
  generateStandard,
  getEventInfo
} from '@/api/bomCompareTool/originInstallationList/index';
import { addStructureMenu } from '@/api/elementsLibrary/index';
import { originInstallationVo, originInstallationQuery, originInstallationForm } from '@/api/bomCompareTool/originInstallationList/type';
import { UploadProps } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tableDatas = ref<originInstallationVo[]>();
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);
const buttonLoading = ref(false);
const router = useRouter();
const queryFormRef = ref<ElFormInstance>();
const dialogFormRef = ref<ElFormInstance>();
const airModelList = ref([]);
const groupTypeOptions = ref([]);
const trackOptions = ref([]);
const data = reactive<PageData<originInstallationForm, originInstallationQuery>>({
  form: {},
  queryParams: {
    aircraftModel: 'C919',
    track: '',
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    aircraftModel: [{ required: true, message: '机型不能为空', trigger: 'change' }],
    file: [{ required: true, message: '原始清单文件不能为空', trigger: 'blur' }],
    track: [{ required: true, message: '所属批次不能为空', trigger: 'change' }],
    groupType: [{ required: true, message: '所属部段不能为空', trigger: 'blur' }],
    isAll: [{ required: true, message: '是否为全机数据不能为空', trigger: 'blur' }]
  }
});
const { queryParams, rules } = toRefs(data);
const fileType = ref('.xls,.xlsx');
const confirmVisible = ref(false);
const originDialog = ref<any>({
  title: '上传原始装机清单',
  visible: false
});
const dialogForm = ref<originInstallationForm>({
  aircraftModel: '',
  track: '',
  desc: '',
  groupType: '',
  isAll: 1,
  file: null
});
const multipleSelection = ref([]);
/**
 * 查询角色列表
 */
const getList = () => {
  loading.value = true;
  getOriginList(queryParams.value).then((res) => {
    tableDatas.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置 */
const resetQuery = () => {
  // dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
// 文件上传函数
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  dialogForm.value.file = null;
  dialogFormRef.value.validateField(['file']);
};
// 数据文件
const handleBefore: UploadProps['beforeUpload'] = (file) => {
  // let limit100M = file.size / 100 / 1024 / 1024 >= 1;
  // if (limit100M) {
  //     proxy?.$modal.msgError("单个文件大小应该小于100M！")
  //     return false
  // }
  const arr = file.name.split('.');
  const type = '.' + arr[arr.length - 1];
  const types = fileType.value.split(',');
  if (fileType.value && !types.includes(type)) {
    proxy?.$modal.msgError('请上传' + fileType.value + '文件！');
    return false;
  }
  return true;
};
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  proxy?.$modal.msgWarning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + uploadFiles.length} 个文件！`);
};
const handleChange: UploadProps['onChange'] = (file: any, uploadFiles) => {
  const flag = handleBefore(file);
  if (!flag) {
    return false;
  }
  if (file.status === 'ready') {
    dialogForm.value.file = file.raw;
    dialogFormRef.value.validateField(['file']);
  }
};
const handleOriginUpload = () => {
  originDialog.value.visible = true;
};
// 上传文件创建标准装机清单
const handleSure = async () => {
  buttonLoading.value = true;
  addStructureTrack();
  let params = new FormData();
  params.append('file', dialogForm.value.file);
  params.append('aircraftModel', dialogForm.value.aircraftModel);
  params.append('track', dialogForm.value.track);
  params.append('desc', dialogForm.value.desc);
  if (!dialogForm.value.isAll) {
    params.append('groupType', dialogForm.value.groupType);
  }
  const res = await uploadOriginListData(params).catch(() => {
    buttonLoading.value = false;
  });
  const timer = setInterval(async () => {
    const ids = res.data.join(',');
    const datas = await getEventInfo({ ids: ids }).catch(() => {
      clearInterval(timer);
      buttonLoading.value = false;
    });
    const data = datas[0];
    proxy?.$modal.msg(`${data.currentInfo}`);
    if (data.status === 'DONE' || data.status === 'FAIL' || data.status === 'NONE_MATCH') {
      clearInterval(timer);
      proxy?.$modal.msgSuccess('上传的原始装机清单数据保存成功!');
      buttonLoading.value = false;
      handleQuery();
      originDialog.value.visible = false;
    }
  }, 1000);
};
const handleCancel = () => {
  originDialog.value.visible = false;
};
const handleDelete = async () => {
  if (!multipleSelection.value.length) {
    proxy?.$modal.msgWarning('请选择要删除的数据!');
    return false;
  }
  await proxy?.$modal.confirm('确认是否删除该笔原始装机清单数据');
  const ids = multipleSelection.value.map((item) => item.id).join(',');
  await originalInfoDelete(ids);
  proxy?.$modal.msgSuccess('删除成功!');
  getList();
};
const handleDataView = (row: any) => {
  router.push({ path: '/modelCompareTools/dataView', query: { id: row.id } });
};
const modelList = async () => {
  const res = await getStructureTree();
  airModelList.value = res.data.map((item) => {
    return {
      value: item.mark,
      label: item.name,
      children: item.children,
      id: item.id
    };
  });
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const handleGenerateStandard = async () => {
  if (!multipleSelection.value.length) {
    proxy?.$modal.msgWarning('请选择数据!');
    return false;
  }
  if (multipleSelection.value.length > 1) {
    proxy?.$modal.msgWarning('请选择一条数据!');
    return false;
  }
  const data = multipleSelection.value[0];
  if (data.status === 'DONE' && data.bizStep === 'OBOM_SBOM_CONVERT') {
    proxy?.$modal.msgWarning('已生成标准装机清单，请重新选择!');
    return false;
  }
  buttonLoading.value = true;
  const obj = {
    aircraftModel: queryParams.value.aircraftModel,
    originalBomId: data.id
  };
  const res = await generateStandard(obj).catch(() => {
    buttonLoading.value = false;
  });
  const timer = setInterval(async () => {
    const ids = res.data.join(',');
    const datas = await getEventInfo({ ids: ids }).catch(() => {
      clearInterval(timer);
      buttonLoading.value = false;
    });
    const data = datas[0];
    proxy?.$modal.msg(`${data.currentInfo}`);
    if (data.status === 'DONE' || data.status === 'FAIL' || data.status === 'NONE_MATCH') {
      clearInterval(timer);
      getList();
      proxy?.$modal.msgSuccess('标准装机清单生成成功!');
      buttonLoading.value = false;
      confirmVisible.value = true;
    }
  }, 1000);
};
const handleClose = () => {
  confirmVisible.value = false;
};
const handleView = () => {
  router.push({ path: '/modelCompareTools/standardInstallationList' });
};
const handleDownloadTemplate = () => {
  const url = '/originalSample.xlsx';
  window.open(url, '_blank');
};
const handleFieldChange = () => {
  if (dialogForm.value.aircraftModel) {
    const obj = airModelList.value.find((item) => item.value === dialogForm.value.aircraftModel);
    if (obj && obj.children) {
      trackOptions.value = obj.children;
      if (dialogForm.value.track) {
        const newObj = obj.children.find((item) => item.mark === dialogForm.value.track);
        if (newObj && newObj.children) {
          groupTypeOptions.value = newObj.children.map((item) => {
            return {
              value: item.mark,
              label: item.name + '[' + item.mark + ']'
            };
          });
        }
      }
    }
  }
};
const addStructureTrack = () => {
  const obj = groupTypeOptions.value.find((item) => item.mark === dialogForm.value.track);
  if (!obj) {
    const newObj = airModelList.value.find((item) => item.value === dialogForm.value.aircraftModel);
    if (newObj) {
      const data = {
        name: dialogForm.value.track,
        mark: dialogForm.value.track,
        taskDefault: 1,
        parentId: newObj.id,
        level: 2
      };
      addStructureMenu(data).then((res) => {
        proxy?.$modal.msgSuccess('已将新的批次创建到构型定义!');
      });
    }
  }
};
onMounted(() => {
  modelList();
  getList();
});
</script>
<style scoped>
.dialog-footer {
  text-align: center;
}
.dialog-btn {
  color: #409eff;
  cursor: pointer;
}
.dialog-btn:hover {
  color: #1984ef;
}
.upload-item {
  position: relative;
}
.download-template {
  position: absolute;
  left: 120px;
  top: 0px;
}
</style>
